<template>
  <div>
    <BasicModal
      :showCancelBtn="false"
      :maskClosable="true"
      :width="800"
      :okText="$t('table.system.system_conform_save')"
      :title="setTitle"
      @register="registerModal"
      @ok="submitOk"
    >
      <BasicForm :size="FORM_SIZE" @register="registerForm">
        <template #siteManage>
          <span class="primary-color cursor-pointer" @click="handlesite">{{
            $t('business.common_edit')
          }}</span>
        </template>
      </BasicForm>
    </BasicModal>
    <siteManage
      @emitList="emitListChange"
      @register="registerSite"
      :sites="getEditSite"
      :edit="true"
      @submitOk="setSiteList"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { insertForm } from './index.data';
  import { useFormSetting } from '/@/hooks/setting/useFormSetting';
  import siteManage from './components/siteManage.vue';
  import { insertAdminList, updateAdminAccount } from '/@/api/sys/index';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';
  const FORM_SIZE = useFormSetting().getFormSize;
  import { useI18n } from '/@/hooks/web/useI18n';
  import { onMounted } from 'vue';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  const { t } = useI18n();
  const openState = ref(false as any);
  const userStore = useUserStore();
  const defaultDdata = ref({});
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    showActionButtonGroup: false,
    schemas: insertForm,
    baseColProps: { span: 24 },
  });
  const siteList = ref(<any>[]);
  const siteListValue = ref([] as any);
  const siteListDeflut = ref([] as any);
  const getEditSite = ref([] as any);
  const setTitle = ref('' as any);
  const editId = ref('' as any);
  const emit = defineEmits(['register', 'successEmit']);
  const [registerSite, { openModal }] = useModal();
  const { clipboardRef, copiedRef, clearClipboard } = useCopyToClipboard();
  const [registerModal, { closeModal }] = useModalInner((data) => {
    //console.log(data);
    const resultArray = [];
    for (const key in data.sites) {
      if (data.sites.hasOwnProperty(key)) {
        const value = data.sites[key];
        resultArray.push(value as never);
      }
    }
    console.log(userStore.siteList);
    siteList.value = userStore.siteList;
    const arrList = [];
    console.log(arrList);
    siteListDeflut.value = arrList;
    siteListValue.value = data.id ? resultArray : arrList;
    resetFields();
    editId.value = data.id;
    setTitle.value = t('modalForm.system.system_add_username');
    getEditSite.value = [];
    if (data.id) {
      defaultDdata.value = data;
      getEditSite.value = data.sites;
      setTitle.value = t('modalForm.system.system_edit_username');
      data.group_id = data.group_id.toString();
      const { password, ...arg } = data;
      setFieldsValue({ ...arg, group_id: data.group_id > 10 ? data.group_id : null });
    } else {
      defaultDdata.value = {};
      const secret = window.otplib.authenticator.generateSecret(40);
      setFieldsValue({ seamo: secret });
    }
  });
  function handlesite() {
    openState.value = true;
    // console.log(defaultDdata.value.id);
    if (!!!defaultDdata.value.id) openModal(true, { type: 'add', data: {} });
    else openModal(true, { type: 'edite', data: defaultDdata.value });
  }

  function refresh() {
    const secret = window.otplib.authenticator.generateSecret(40);
    setFieldsValue({ seamo: secret });
    return Promise.reject();
  }

  function setSiteList() {
    siteList.value = ['1'];
  }

  function handleCopy(value) {
    if (!value) {
      message.warning(t('business.common_copy_tip'));
      return;
    }
    clearClipboard();
    clipboardRef.value = value;
    if (unref(copiedRef)) {
      message.success(t('business.common_copy_suceess'));
    }
  }

  function emitListChange(v) {
    siteListValue.value = v;
    getEditSite.value = v;
  }
  async function submitOk() {
    const values = await validate();
    //console.log(values)
    // console.log(siteListValue.value)
    if (siteListValue.value.length == 0) {
      message.error(t('table.system.system_management_site_not_selected'));
      return;
    }
    const uniqueArr = [...new Set(siteListValue.value)];
    // console.log(uniqueArr);
    let _data = {
      username: values?.username,
      nickname: values?.nickname,
      password: values?.password, //密码
      group_id: values?.group_id, //用户组id
      sites: uniqueArr,
      seamo: values?.seamo, //动态密码给固定值
      remark: values?.remark,
    };
    editId.value ? (_data['id'] = editId.value) : _data;
    if (editId.value) {
      if (_data.password) {
        const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');

        if (reg.test(_data.password)) {
          message.error(t('table.system.system_including_cn'));
          return;
        }

        const reg2 = new RegExp('^[a-zA-Z0-9]{6,20}$', 'g');

        if (!reg2.test(_data.password)) {
          message.error(t('table.system.system_login_tips'));
          return;
        }
      } else {
        delete _data.password;
      }
    }

    const { status, data } = editId.value
      ? await updateAdminAccount(_data)
      : await insertAdminList(_data);
    console.log(status);
    if (status) {
      emit('successEmit');
      message.success(data);
      closeModal();
    } else {
      emit('successEmit');
      message.error(data);
    }
  }
  onMounted(() => {
    siteListValue.value = siteListDeflut.value;
  });
</script>

<style lang="less">
  .addmoneyBox {
    width: 100%;
    padding: 0 5px;
    border: 1px solid #d9d9d9;
    border-radius: 3px;

    .header {
      width: 600px;
    }
  }
</style>
